<template>
  <!-- 导入基本数据 -->
  <a-modal
    :visible="importExeclVisible"
    title="一卡通账号待确认表"
    centered
    :closable="false"
    width="80%"
    dialogClass="member-execl-dialog"
    @cancel="importExeclVisible = false"
  >
    <layout>
      <!-- 产品列表 -->
      <a-table
        :dataSource="tableData"
        :columns="tableColumns"
        :rowKey="(record) => record.member_id"
        :customRow="customTableRow"
        :pagination="false"
        size="small"
        :scroll="{
          x: '100%',
          y: 520,
        }"
        bordered
      >
        <!-- 按钮区 -->
      </a-table>

      <a-pagination
        slot="paging"
        :pageSizeOptions="pageSizes"
        :total="total"
        :show-total="showTotal"
        showSizeChanger
        :pageSize="pageSize"
        v-model="currentPage"
        @showSizeChange="changePageSize"
        @change="changePage"
      >
      </a-pagination>
    </layout>
    <section slot="footer">
      <a-button @click="importExeclVisible = false">取消</a-button>
      <a-button
        type="primary"
        :loading="importExeclConfirmLoading"
        @click="handlerConfirmImport(0)"
        >{{ isPreview ? '待上传文件内容已确认' : '增量导入' }}</a-button
      >
    </section>
  </a-modal>
</template>

<script lang="ts">
import { Vue, Component, Prop, Mixins, Watch } from 'vue-property-decorator'
import { ImportExecl } from '@/utils/execl'
import { famerServices, IMember } from '@/common/services/famer'
import ImportExeclPreview from './MemberImportExeclPreview.vue'
import MemberImportErrors from './MemberImportErrors.vue'
import { message, Modal } from 'ant-design-vue'
import { BUSINESS_CODE } from '@/api/interceptors'
import { isIDCard } from '@/utils/tools'
import { userModule } from '@/store/modules/user'

import { TableLayout } from '@/layouts'

import EventsMixin from '@/mixin/events'
import { TableMixin, AuthMixin } from '@/mixin'
import { cropMemberServices } from '@/common/services/crop-member'

@Component({
  components: {
    ImportExeclPreview,
    MemberImportErrors,
    layout: TableLayout
  },
})
export default class MemberYKTAccountImport extends Mixins(
  EventsMixin,
  TableMixin,
  AuthMixin
) {
  @Prop({
    type: Boolean,
    default: false,
  })
  public isPreview!: boolean

  @Prop({
    type: String,
  })
  public currentAreaId!: string

  get isPlant() {
    return userModule.isPlant
  }

  // Execl预览信息
  public tableData = []
  public columns: ITable.IColumn[] = []

  // Execl字段信息
  public execlFields: Record<string, string> = {}

  // 上传execl
  public importExeclVisible = false
  public importExeclConfirmLoading = false
  public execlData = []
  public file!: File
  public handlerUploadExecl() {
    let fields: Record<string, string> = this.execlFields = {
      member_id: '农户编号',
      member_nam: '户主姓名',
      member_sfz: '身份证号',
      member_bank_num: '一卡通号',
      member_bank_code: '开户行名',
    }
    this.columns = this.getTableColumn();
    ImportExecl(fields, (data, map) => {
      // 提取表头信息
      const [first] = data.slice(0, 1)
      let tempFields = Object.assign({}, first)

      for (const i in tempFields) {
        let value = tempFields[i]
        tempFields[value] = i
        delete tempFields[i]
      }

      for (const i in fields) {
        const hasKey = tempFields[fields[i]]
        if (hasKey) {
          fields[i] = hasKey
        }
      }

      data = data.slice(1)
      // 验证农户信息判定农户姓名去掉空格后长度≥4字符(且不包含“合计"二字)，且身份证号长度去空格后≥15字符
      if (data.length) {
        data = data.filter((item: any) => {
          return `${item[fields['member_nam']]}`.trim().length >= 2 && `${item[fields['member_nam']]}`.indexOf('合计') === -1 && `${item[fields['member_sfz']]}`.trim().length >= 15
        })
      }

      return {
        fields: fields,
        data,
      }
    }).then((_) => {
      this.importExeclVisible = true
      // @ts-ignore
      this.execlData = this.formatIDCardError(_.formatedData) || []
      console.log(this.execlData)
      // @ts-ignore
      this.file = _.file
    })
  }

  @Watch('execlData', { immediate: true })
  public handlerChangeExecl() {
    this.total = this.execlData.length
    this.getData()
  }

  public async getData() {
    this.tableData = this.execlData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
  }

  // 获取Execl表头
  public getTableColumn() {
    return Object.keys(this.execlFields).map(key => {
      return {
        key: key,
        title: this.execlFields[key],
        dataIndex: key
      }
    })
  }

  public formatIDCardError(data: any[]) {
    return data.map((item) => {
      if (!isIDCard(item.member_sfz)) {
        return {
          ...item,
          error: true,
        }
      }
      return item
    })
  }

  public handlerConfirmImport(type: number = 0) {
    this.$confirm({
      title: '导入提示',
      content:
        type === 0
          ? '本次导入数据将更新或追加到当前选择行政区，确认导入？'
          : '本次导入数据将替换当前选择行政区数据（原数据将被删除，不能在线恢复），确认导入？',
      onOk: () => {
        this.handlerImport(type)
      },
    })
  }

  public async handlerImport(type: number) {
    // @ts-ignore
    const data = this.execlData
    if (!data.length) {
      message.error('请导入数据')
      return false
    }

    // 预览模式下直接返回数据 + 关闭
    if (this.isPreview) {
      this.$emit('previewSuccess', {
        data,
        file: this.file,
      })
      this.importExeclVisible = false
      return
    }

    this.importExeclConfirmLoading = true

    const api = this.isPlant ? cropMemberServices.ImportYKTAccount : famerServices.ImportYKTAccount
    api({
        data,
        file_nam: this.file.name,
        s_a_id: this.currentAreaId,
      })
      .then((_) => {
        const res = _.data
        if (res.code === BUSINESS_CODE.SUCCESS) {
          Modal.success({
            content: '数据导入成功',
            centered: true,
          })
        } else if (res.code === BUSINESS_CODE.ERROR) {
           Modal.error({
            content: res.msg,
            centered: true,
          })
        } else {
          this.$dialog(
            MemberImportErrors,
            {
              messages: res.msg.map((str) => ({ content: str })),
            },
            {
              title: '异常数据列表',
              width: '60%',
              footer: null,
            }
          )
        }
      })
      .finally(() => {
        this.importExeclVisible = false
        this.importExeclConfirmLoading = false
      })
  }
}
</script>

<style lang="less" scoped>
.member-container {
  display: flex;
  .area-tree {
    width: 300px;
    flex: none;
    background-color: #fff;
    border-right: 1px solid #eee;
    margin-right: 10px;
  }
}
.house-holder /deep/ .ant-card-body {
  max-height: 600px;
  height: auto;
}
.member-list {
  display: flex;
  flex-direction: column;
}
</style>
